<template>
  <div class="pagewrapper p-20">
    <div class="bg_fff pagebox h_full flex">
      <company-left :repoType="repoType" @handleItem="handleGroup" />
      <div class="pageright">
        <div ref="pageheader">
          <div class="c_text2 r_title f-14">全部话术</div>
          <div class="flexbetween p-12 pb-0">
            <el-form
              :model="queryParams"
              ref="queryForm"
              size="small"
              class="headerquery"
              :inline="true"
            >
              <el-form-item>
                <el-button
                  class="f-14 f14btn"
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="small"
                  @click="handleAdd"
                  v-hasPermi="['system:reply:add']"
                >
                  添加话术
                </el-button>
              </el-form-item>
              <el-form-item label="" prop="title">
                <el-input
                  v-model="queryParams.title"
                  placeholder="搜话术"
                  clearable
                  style="width: 180px"
                  @keyup.enter.native="handleQuery"
                  suffix-icon="el-icon-search"
                />
              </el-form-item>
              <el-form-item prop="contentDesc">
                <el-select
                  v-model="queryParams.contentDesc"
                  @change="handleQuery"
                  style="width: 130px"
                  placeholder="请选择类型"
                >
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-button plain size="small" class="f-14" @click="resetQuery">
                重置
              </el-button>
            </el-form>
            <div class="flex aligncenter mb-18">
              <el-button v-hasPermi="['system:reply:export']" size="small" class="f-14 f14btn ml-8" plain
                >导出</el-button
              >
              <el-button v-hasPermi="['system:reply:leadinto']" size="small" class="f-14 f14btn mr-8">
                导入
              </el-button>
              <el-tooltip
                class="item"
                effect="dark"
                content="仅支持文本话术导出和导入"
                placement="top-start"
              >
                <i class="el-icon-info"></i>
              </el-tooltip>
            </div>
          </div>
        </div>
        <el-table v-loading="loading" :height="total>0?tableHeight:'auto'" :data="tableList" row-key="id">
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
          <el-table-column v-if='queryParams.groupId == -2'
            label="排序"
            prop="userName"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{(queryParams.pageNum - 1) * queryParams.pageSize +scope.$index + 1}}
            </template>
          </el-table-column>
          <el-table-column v-else
            label="排序"
            prop="userName"
            :show-overflow-tooltip="true"
            class-name="allowDrag"
          >
            <!--  slot-scope="scope" -->
            <template>
              <svg-icon class-name="f-14" icon-class="sort" style="cursor:grab" />
              <!-- {{(queryParams.pageNum - 1) * queryParams.pageSize +scope.$index + 1}} -->
            </template>
          </el-table-column>
          <el-table-column
            label="标题"
            prop="userName"
            min-width="360px"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <div class="f-14 c_text2">{{ scope.row.title || "-" }}</div>
              <div class="f-13 c_text3">
                {{ scope.row.update_time || "2023-12-13 09:11" }}
                <span class="pl-8">分组：{{ scope.row.groupName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="话术内容"
            prop="nickName"
            min-width="300px"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <div class="f-14 c_text2">
                {{ scope.row.contentDesc || "-" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="类型"
            prop="email"
            min-width="120px"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <el-tag type="info">{{ scope.row.type }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            min-width="220"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['system:reply:detail']"
                type="text"
                @click="handleDetail(scope.row)"
                >查看</el-button
              >
              <el-button
                v-hasPermi="['system:reply:edit']"
                type="text"
                @click="handleEdit(scope.row)"
                >编辑</el-button
              >
              <el-button
                v-hasPermi="['system:reply:copy']"
                type="text"
                @click="handleCopy(scope.row)"
                >复制</el-button
              >
              <el-button
                v-hasPermi="['system:reply:delete']"
                type="text"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
              <el-dropdown v-if='queryParams.groupId !== -2' v-hasPermi="['system:reply:sort']" @command="handleCommand($event, scope.$index)">
                <el-button type="text">排序</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="a">置顶</el-dropdown-item>
                  <el-dropdown-item command="b">上移</el-dropdown-item>
                  <el-dropdown-item command="c">下移</el-dropdown-item>
                  <el-dropdown-item command="d">置底</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          class="mt-0"
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    <!-- 添加编辑话术 -->
    <add-reply
      v-if="addopen"
      :visable="addopen"
      :rowitem='rowitem'
      :title="title"
      @close="handleClose"
    />
    <!-- 详情 -->
    <detail-reply
      v-if="detailopen"
      :visable="detailopen"
      :rowitem='rowitem'
      @close="handleDetailClose"
    />
  </div>
</template>
<script>
import { scriptItemList, changeOrder, delScriptItem } from "@/api/market/reply";
import CompanyLeft from "./CompanyLeft.vue";
import AddReply from "./components/AddReply.vue";
import DetailReply from "./components/DetailReply.vue";
import tablemixins from '@/mixins/tablemixins';
import Sortable from 'sortablejs'

export default {
  data() {
    return {
      loading: false,
      statusOptions: [
        { name: "推荐客服名片", id: 1 },
        { name: "文本", id: 2 },
        { name: "图片", id: 3 },
        { name: "语音", id: 4 },
        { name: "图文链接", id: 5 },
        { name: "视频", id: 6 },
        { name: "文件", id: 7 },
        { name: "小程序", id: 8 },
        { name: "名片", id: 9 },
        { name: "系统消息", id: 10 },
        { name: "视频号", id: 11 },
        { name: "公告", id: 12 },
        { name: "聊天集合", id: 13 },
        { name: "红包", id: 14 },
        { name: "表情", id: 15 },
        { name: "接龙", id: 16 },
        { name: "定位", id: 17 },
        { name: "语音视频通话", id: 18 },
        { name: "商品", id: 19 },
        { name: "二维码", id: 20 },
        { name: "小程序码", id: 21 }
      ],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupId: "",
        contentDesc:undefined,
        title:undefined 
      },
      total: 0,
      tableList: [],
      addopen: false,
      title: "",
      detailopen: false,
      rowitem:null
      //   form: {
      //     name: "",
      //     status: 0,
      //   },
      //   rules: {
      //     name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
      //   },
    };
  },
  mixins: [tablemixins],
  components: {
    CompanyLeft,
    AddReply,
    DetailReply,
  },
  props: {
    repoType: {
      require: true,
      default: 1,
    },
  },
  mounted(){
    this.rowDrop()
  },
  methods: {
    handleGroup(item) {
      console.log("点击了11", item);
      this.queryParams.groupId = item.id;
      this.queryParams.repoType = this.repoType
      this.getList();
    },

    getList() {
      this.loading = true;
      scriptItemList(this.queryParams)
        .then((response) => {
          this.tableList = response.itemList;
          this.total = response.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    handleAdd() {
      this.title = "新建话术";
      this.addopen = true;
    },

    handleClose(type) {
      if (type == 1) {
        this.getList();
      }
      this.addopen = false;
      this.rowitem = null;
    },

    handleEdit(row) {
      this.rowitem = row
      this.title = "编辑话术";
      this.addopen = true;
    },

    handleCopy(row) {
      this.rowitem = row
      this.title = "复制话术";
      this.addopen = true;
    },

    handleDetail(row) {
      this.rowitem = row
      this.detailopen = true;
    },

    handleDetailClose() {
      this.detailopen = false;
      this.rowitem = null
    },

    handleDelete(row) {
      this.$msgBox.showMsgBox({
          title: "提示？",
          content: "删除后将无法恢复，是否确认删除？",
        })
        .then( () => {
          delScriptItem(row.id).then(()=>{
            this.$message.success('删除成功!')
            this.getList()
          })
        })
        .catch(() => {});
    },

    handleCommand(command, index) {
      // console.log(command)
      switch (command) {
        case "a"://置顶
          let arra =  [...this.tableList];
          arra.unshift(arra.splice(index, 1)[0]);
          this.handleUpdateIndex(arra)
          break;
        case "b"://上移
          let arrb = [...this.tableList];
          arrb.splice(index - 1, 1, ...arrb.splice(index, 1, arrb[index - 1]));
          this.handleUpdateIndex(arrb)
          break;
        case "c"://下移
          let arrc = [...this.tableList];
          arrc.splice(index, 1, ...arrc.splice(index + 1, 1, arrc[index]));
          this.handleUpdateIndex(arrc)
          break;
        case "d"://置底
          let arrd = [...this.tableList];
          arrd.push(arrd.splice(index, 1)[0]);
          this.handleUpdateIndex(arrd)
          break;
        default:
          break;
      }
    },

    // 排序
    handleUpdateIndex(arr){
      let params = {
        groupId: this.queryParams.groupId,
        itemList: arr.map((item,index)=>({
          id:item.id,
          itemOrderIndex:index+1
        }))
      }
      // arr.forEach((item,index) => {
      //   params.itemList.push({id:item.id,itemOrderIndex:index+1})
      // });
    
      console.log('params:', JSON.stringify(params))
      changeOrder(params).then(res=>{
        this.getList()
      })
    },

    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (!valid) return;
      });
    },

    handleItem(item) {
      this.active = item.id;
    },

    // 行拖拽
    rowDrop() {
      // 要侦听拖拽响应的DOM对象（数据存储在.el-table__body-wrapper > .el-table__row > tbody标签中（el-table的数据部分的“最外层”class名为el-table__body-wrapper））
      const tbody = document.querySelector('.el-table__body-wrapper tbody');
      const that = this;
      Sortable.create(tbody, {
        handle: ".allowDrag",
        // 结束拖拽后的回调函数
        onEnd({ newIndex, oldIndex }) {
          console.log('拖动了行，序号(index)"' + oldIndex + '"拖动到序号(index)"' + newIndex + '"');
          const currentRow = that.tableList.splice(oldIndex, 1)[0]; // 将oldIndex位置的数据删除并取出，oldIndex后面位置的数据会依次前移一位
          console.log('currentRow:', currentRow)
          that.tableList.splice(newIndex, 0, currentRow); // 将被删除元素插入到新位置（currRow表示上面的被删除数据）
          // that.$nextTick(function () {
          //   that.tableList = that.tableList;
          // });
          that.handleUpdateIndex(that.tableList)

          // let params = {
          //   groupId: this.queryParams.groupId,
          //   itemList: this.tableList.map((item,index)=>({
          //     id:item.id,
          //     itemOrderIndex:index+1
          //   }))
          // }
          // that.$nextTick(function () {
          //   that.tableList = that.tableList;
          // });
        }
      })
    }
  },
};
</script>

<style lang="scss" scoped>
.pagebox {
  border-radius: 4px;
}
.pageright {
  flex: 1;
  min-height: 100%;
  overflow: hidden;
}
.role-header {
  height: 64px;
  border-bottom: 1px solid #e0e0e0;
}
.infotitle {
  width: 160px;
  text-align: right;
}
.r_title {
  padding: 12px 0px 0px 12px;
}
</style>